package io.github.topcatv.mall.model.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Sets;
import io.github.topcatv.mall.model.sys.entity.Role;
import io.github.topcatv.mall.model.sys.entity.RolePermission;
import io.github.topcatv.mall.model.sys.mapper.RoleMapper;
import io.github.topcatv.mall.model.sys.service.IRolePermissionService;
import io.github.topcatv.mall.model.sys.service.IRoleService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liuyi
 * @since 2019-10-14
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Resource
    IRolePermissionService rolePermissionService;

    @Override
    public Set<Role> selectByUserId(Integer id) {
        return baseMapper.selectByUserId(id);
    }

    @Override
    public void addPermissions(Integer id, Integer[] permissionIds) {
        QueryWrapper<RolePermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(RolePermission::getRoleId, id);
        rolePermissionService.remove(queryWrapper);
        Collection<RolePermission> rolePermissions = Sets.newHashSet();
        if (ArrayUtils.isNotEmpty(permissionIds)) {
            for (Integer permissionId : permissionIds) {
                RolePermission rolePermission = new RolePermission();
                rolePermission.setRoleId(id);
                rolePermission.setPermissionId(permissionId);
                rolePermissions.add(rolePermission);
            }
        }
        rolePermissionService.saveBatch(rolePermissions);
    }
}
